import { defineStore } from 'pinia'
import { lazyTree,fetchAllNodes, createTreeNode, renameTreeNode, deleteTreeNode, moveTreeNode, copyTreeNode, swapTreeNode, unitedTreeNode } from '@/api/api'
import { getProjectOne } from '@/api/project'
import { getApiDoc, getApiDocList, addApiDoc, updateApiDoc } from '@/api/apiDoc'
import { getQuickDoc, createQuickDoc, updateQuickDoc, deleteQuickDoc, renameQuickDoc } from '@/api/apiQuickDoc'
import {
    getProjectEnvList,
    getProjectEnvOne,
    createProjectEnv,
    updateProjectEnv,
} from "@/api/projectEnv";
import router from '../router'
import { set } from '@vue/composition-api';
import { nextTick } from '@vue/composition-api';
export const useApiStore = defineStore('api', {
    state: () => ({
        id: '',
        type: '',
        key: '',
        projectId: '',
        apiTreeRootId: '',
        projectName: '',
        tagId: '',
        docId: '',
        treeType: '',
        sortList: [],
        tagList: [],
        docList: [],
        docTotal: 0,
        docPageQuery: {
            page: 1,
            pageSize: 10,
        },
        doc: null,
        envId: null,
        env: {},
        envOptionList: [],

        treeList: [],
        apiMenuRootId: null,
        quickReqMenuRootId: null,
        startMenuRootId: null,
        parentId: null,
        treeComponent: null,

        tabList: [],
        tabActive: null,

        statusOptions: [
            { label: '开发中', value: 0 },
            { label: '已发布', value: 1 },
            { label: '联调中', value: 2 },
            { label: '已废弃', value: 3 },
        ]
    }),
    getters: {
    },
    actions: {
        refresh() {
            this.fetchLazyTree({data: {}})
        },
    
        toBlankQuick() {
            this.doc = {}
            this.docId = parseInt(10000 * Math.random(), 0) * -1
            this.replaceTab('快捷请求', this.docId, 2)
        },
        tabClick(name) {
            if ('__plus__' === name) {
                return
            }
            const tab = this.tabList.find(item => item.key === name)
            this.docId = Number(tab.name)
            // const treeType = tab.treeType
            // if (this.docId === -10) {
            //     router.replace({
            //         name: "api-index",
            //         query: {
            //             ...router.currentRoute.query,
            //             docId: this.docId,
            //         },
            //     });
            // } else if (treeType === 1) {
            //     router.replace({
            //         name: "api-detail",
            //         query: {
            //             ...router.currentRoute.query,
            //             docId: this.docId,
            //         },
            //     });
            // } else if (treeType === 2) {
            //     router.replace({
            //         name: "api-quick",
            //         query: {
            //             ...router.currentRoute.query,
            //             docId: this.docId,
            //         },
            //         params: {
            //             operate: 'tabClick'
            //         }
            //     });
            // }

        },

        replaceTab(title, newDocId, treeType) {
            const newTab = this.tabList.find(item => item.key === treeType + '' + newDocId)
            const tab = this.tabList.find(item => item.key === this.tabActive)
            if (newTab) {
                this.tabActive = newTab.key
            } else {
                tab.title = title
                tab.name = newDocId
                tab.treeType = treeType
                tab.key = treeType + '' + newDocId
                this.tabActive = treeType + '' + newDocId
            }

            // router.replace({
            //     name: "api-quick",
            //     query: {
            //         ...router.currentRoute.query,
            //         docId: newDocId,
            //     },
            // });
        },

        removeTab(key) {
            const index = this.tabList.findIndex(item => item.key === key)
            let targetKey = key
            if (index !== -1) {
                if (key === this.tabActive) {
                    if (this.tabList.length > 1) {
                        if (index === this.tabList.length - 1) {
                            this.docId = Number(this.tabList[index - 1].name)
                            targetKey = this.tabList[index - 1].key
                        } else if (index === 0) {
                            this.docId = Number(this.tabList[1].name);
                            targetKey = this.tabList[1].key
                        } else {
                            this.docId = Number(this.tabList[index - 1].name)
                            targetKey = this.tabList[index - 1].key
                        }
                    } else {
                        this.docId = ''
                        targetKey = ''
                    }
                }
                this.tabActive = targetKey
                this.tabList.splice(index, 1)

                // if (this.docId === -10) {
                //     router.replace({
                //         name: "api-index",
                //         query: {
                //             ...router.currentRoute.query,
                //             docId: this.docId,
                //         },
                //     });
                // } else if (this.docId) {
                //     router.replace({
                //         name: "api-quick",
                //         query: {
                //             ...router.currentRoute.query,
                //             docId: this.docId,
                //         },
                //     });
                // } else {
                //     // router.replace({
                //     //     name: router.currentRoute.name,
                //     //     query: {
                //     //         ...router.currentRoute.query,
                //     //         docId: this.docId,
                //     //     },
                //     // });
                // }
            }
        },

        addTab(title, docId, treeType) {
            const index = this.tabList.findIndex(item => item.key === treeType + '' + docId)
            if (index !== -1) {

            } else {
                this.tabList.push({
                    key: treeType + '' + docId,
                    title,
                    treeType,
                    name: docId,
                })
                this.tabActive = treeType + '' + docId
            }
            // if (docId === '-10') {
            //     router.replace({
            //         name: "api-index",
            //         query: {
            //             ...router.currentRoute.query,
            //             docId,
            //         },
            //     });
            // } else {
            //     router.replace({
            //         name: "api-quick",
            //         query: {
            //             ...router.currentRoute.query,
            //             docId,
            //         },
            //     });
            // }

        },

        fetchQuickDoc() {
            this.doc = null
            return getQuickDoc({ id: this.docId })
                .then(res => {
                    const data = res.data
                    this.doc = data
                    // const tab = this.tabList.find(item => item.key === 2 + '' + this.docId)
                    // tab.doc = data
                })
        },

        menuAdd(name, treeId, apiDocId, parentId, type, index) {
            console.log(treeId, apiDocId, parentId)
            const parentNode = this.treeComponent.getNode(parentId)
            // if (parentNode.loaded) {
            //     const subNode = {
            //         parentId,
            //         name,
            //         type,
            //         id: treeId,
            //         apiDocId: apiDocId,
            //         children: [],
            //         index,
            //         leaf: true,
            //         treeType: parentNode.data.treeType
            //     }
            //     this.treeComponent.append(subNode, parentNode)
            //     nextTick(() => {
            //         parentNode.isLeaf = false
            //         parentNode.expanded = true
            //         parentNode.loaded = true
            //     })
            // } else {
            //     parentNode.loadData(() => {
            //         nextTick(() => {
            //             parentNode.expanded = true
            //         })
            //     })
            // }
            const subNode = {
                parentId,
                name,
                type,
                id: treeId,
                apiDocId: apiDocId,
                children: [],
                index,
                leaf: true,
                treeType: parentNode.data.treeType
            }
            this.treeComponent.append(subNode, parentNode)
            nextTick(() => {
                parentNode.isLeaf = false
                parentNode.expanded = true
                parentNode.loaded = true
            })

        },

        quickNodeMove(node, targetTreeId) {
            console.log(node, targetTreeId)
            const parentNode = this.treeComponent.getNode(targetTreeId)
            this.treeComponent.remove(node)
            node.data.parentId = parentNode.data.parentId
            if (parentNode) {
                // if (parentNode.loaded) {
                //     this.treeComponent.append(node.data, parentNode)
                //     nextTick(() => {
                //         parentNode.isLeaf = false
                //         parentNode.expanded = true
                //         parentNode.loaded = true
                //     })
                // } else {
                //     parentNode.loadData(() => {
                //         nextTick(() => {
                //             parentNode.expanded = true
                //         })
                //     })
                // }
                this.treeComponent.append(node.data, parentNode)
                    nextTick(() => {
                        parentNode.isLeaf = false
                        parentNode.expanded = true
                        parentNode.loaded = true
                    })
            } else {

            }
        },

        fetchLazyTree(node, resolve) {
            if (!node.data.id) {
                fetchAllNodes({rootId: this.apiTreeRootId})
                    .then(res => {
                        const data = res.data
                        this.treeList = data
                        this.startMenuRootId = this.treeList[0].id
                        this.apiMenuRootId = this.treeList[1].id
                        this.quickReqMenuRootId = this.treeList[2].id
                        this.treeList[0].treeType = 0
                        this.treeList[1].treeType = 1
                        this.treeList[2].treeType = 2
                        this.treeList.splice(0, 1)
                    })
            }
            // if (!node.data.id) {
            //     return lazyTree({ parentId: this.apiTreeRootId })
            //         .then(res => {
            //             const data = res.data
            //             this.treeList = data.map(item => ({ children: [], leaf: item.type === 1 || item.subSize === 0, ...item }))
            //             this.startMenuRootId = this.treeList[0].id
            //             this.apiMenuRootId = this.treeList[1].id
            //             this.quickReqMenuRootId = this.treeList[2].id
            //             this.treeList[0].treeType = 0
            //             this.treeList[1].treeType = 1
            //             this.treeList[2].treeType = 2
            //             this.treeList.splice(0, 1)
            //             // this.treeList.splice(0, 1)
            //         })
            // }
            // return lazyTree({ parentId: node.data.id })
            //     .then(res => {
            //         const data = res.data
            //         resolve(data.map(item => ({ treeType: node.data.treeType, children: [], leaf: item.type === 1 || item.subSize === 0, ...item })))
            //     })
        },
        createRootTreeSubNode({ name, type }) {
            return createTreeNode({ name, parentId: this.apiTreeRootId, type })
                .then(res => {
                    const id = res.data.id
                    this.treeList.push({
                        name,
                        type,
                        id,
                        children: [],
                        leaf: true
                    })
                })
        },

        createTreeSubNode({ name, type, parentData, parentNode, component, path, method, tagId, statusId, parameters, requestBody }) {
            const isQuick = parentData.treeType === 2
            return createTreeNode({ name, parentId: parentData.id, type, path, method, tagId, statusId, isQuick, parameters, requestBody })
                .then(res => {
                    const id = res.data.id
                    const apiDocId = res.data.apiDocId
                    const index = res.data.index
                    this.menuAdd(name, id, apiDocId, parentData.id, type, index)
                    if (type === 1) {
                        this.docId = apiDocId
                        this.addTab(name, apiDocId, parentData.treeType)
                    }

                    // component.append({
                    //     name,
                    //     type,
                    //     id,
                    //     apiDocId,
                    //     children: [],
                    //     index: 10000,
                    //     leaf: true,
                    //     treeType: parentData.treeType
                    // }, parentNode)

                    // nextTick(() => {
                    //     parentNode.isLeaf = false
                    //     parentNode.expanded = true
                    //     parentNode.loaded = true
                    // })
                })
        },
        unitedTreeSubNode({parentData, docParentId }) {
            
            return unitedTreeNode({ parentId: parentData.id, docParentId })
                .then(res => {
                    const id = res.data.id
                    const apiDocId = res.data.apiDocId
                    const index = res.data.index
                    this.menuAdd(res.data.name, id, apiDocId, parentData.id, 1, index)
                    this.docId = apiDocId
                    this.addTab(res.data.name, apiDocId, parentData.treeType)

                    // component.append({
                    //     name,
                    //     type,
                    //     id,
                    //     apiDocId,
                    //     children: [],
                    //     index: 10000,
                    //     leaf: true,
                    //     treeType: parentData.treeType
                    // }, parentNode)

                    // nextTick(() => {
                    //     parentNode.isLeaf = false
                    //     parentNode.expanded = true
                    //     parentNode.loaded = true
                    // })
                })
        },

        deleteTreeSubNode(node) {
            return deleteTreeNode({ treeId: node.data.id, isQuick: node.data.treeType === 2 })
                .then(res => {
                    const key = node.data.treeType + '' + node.data.apiDocId
                    this.removeTab(key)
                    this.treeComponent.remove(node.data.id)
                })
        },

        renameTreeSubNode(node, newName) {
            return renameTreeNode({ treeId: node.data.id, name: newName, type: node.data.type, isQuick: node.data.treeType === 2 })
                    .then(res => {
                        node.data.name = newName
                    })
        },

        moveTreeNode(node, targetTreeId) {
            return moveTreeNode({
                treeId: node.data.id,
                targetTreeId
            }).then(() => {
                this.quickNodeMove(node, targetTreeId)
            })
        },

        copyTreeNode(node) {
            return copyTreeNode({ treeId: node.data.id })
                .then(res => {
                    const { docId, treeId, name } = res.data
                    this.menuAdd(name, treeId, docId, node.parent.data.id, 1)
                })
        },

        swapTreeNode(fromNode) {
            const parentNode = this.treeComponent.getNode(fromNode.data.parentId)
            const children = parentNode.childNodes
            console.log(parentNode)
            return swapTreeNode({
                newNodeList: children.map(item => item.data),
                parentId: fromNode.data.parentId
            })
        },

        treeNodeClick(data, node, component) {
            if (data.apiDocId === this.docId && this.treeType === data.treeType) {
                return;
            }
            let isQuick = node.data.treeType === 2
            const isApi = node.data.treeType === 1
            console.log(isQuick, this.quickReqMenuRootId, data.id)
            if (isQuick && this.quickReqMenuRootId !== data.id && node.data.type === 1) {
                this.doc = null
                this.docId = data.apiDocId
                this.treeType = data.treeType
                this.parentId = node.data.id
                // tab组件会把假值变成'0'
                if (this.tabActive && this.tabActive !== '0') {
                    this.replaceTab(node.data.name, this.docId + '', node.data.treeType)
                } else {
                    this.addTab(node.data.name, this.docId + '')
                }
                // router.replace({
                //     name: 'api-quick',
                //     query: {
                //         ...router.currentRoute.query,
                //         docId: this.docId
                //     },
                //     params: {
                //         operate: 'treeClick'
                //     }
                // }, () => {

                // })

                return
            }
            if (isApi && this.apiMenuRootId !== data.id && node.data.type === 1) {
                this.doc = null
                this.docId = data.apiDocId
                this.treeType = data.treeType
                this.parentId = data.parentId
                // tab组件会把假值变成'0'
                if (this.tabActive && this.tabActive !== '0') {
                    this.replaceTab(node.data.name, this.docId + '', node.data.treeType)
                } else {
                    this.addTab(node.data.name, this.docId + '')
                }
                // return router.replace({
                //     name: 'api-detail',
                //     query: {
                //         ...router.currentRoute.query,
                //         docId: data.apiDocId,
                //         // parentId: data.parentId,
                //     }
                // })
                return
            }

            if ([this.startMenuRootId, this.apiMenuRootId, this.quickReqMenuRootId].includes(data.id)) {
                if (this.startMenuRootId === data.id) {
                    this.docId = ''
                    this.doc = null
                    router.replace({
                        name: 'api-index',
                        query: {
                            projectId: this.projectId,
                        }
                    })
                }
            } else {
                if (data.type === 0) {
                    this.parentId = data.id
                    // router.replace({
                    //     name: 'api-list',
                    //     query: {
                    //         ...router.currentRoute.query,
                    //         parentId: data.id
                    //     }
                    // })
                } else if (data.type === 1) {
                    this.docId = data.apiDocId
                    this.parentId = data.parentId
                    router.replace({
                        name: 'api-detail',
                        query: {
                            ...router.currentRoute.query,
                            docId: data.apiDocId,
                            parentId: data.parentId,
                        }
                    })
                }
            }
        },

        // 页面上的保存按钮
        saveQuickDoc(newDoc, parentId) {
            const tmpDoc = JSON.parse(JSON.stringify(newDoc))
            // 更新
            if (this.docId > 0) {
                return updateQuickDoc({
                    docId: this.docId,
                    ...tmpDoc,
                })
            } else { // 创建
                return createQuickDoc({
                    ...tmpDoc,
                    projectId: this.projectId,
                    parentId: parentId || this.quickReqMenuRootId,
                }).then(res => {
                    this.docId = res.data.docId
                    const index = res.data.index
                    // router.replace({
                    //     name: 'api-quick',
                    //     query: {
                    //         ...router.currentRoute.query,
                    //         docId: this.docId
                    //     }
                    // })
                    this.menuAdd(newDoc.summary, res.data.treeId, res.data.docId, parentId || this.quickReqMenuRootId, 1, index)
                    this.replaceTab(newDoc.summary, this.docId + '', 2)
                })
            }
        },

        setData(data) {
            this.id = data.id
            this.type = data.type
            this.key = `${data.type}-${data.id}`
            if (data.type === 'tag') {
                this.tagId = data.id
            }
            if (data.type === 'api') {
                this.docId = data.id
            }
        },

        // destroy() {
        //     this.projectId = null
        //     this.parentId = null
        //     this.docId = ''
        //     this.doc = {}
        //     this.treeList = []
        // },
        init() {
            const route = router.currentRoute
            this.projectId = route.query.projectId
            // this.tagId = route.query.tagId
            // this.docId = route.query.docId
            this.docId = ''
            this.doc = null
            this.treeList = []
            // if (route.name !== 'api-index') {
            //     router.replace({
            //         name: 'api-index',
            //         query: {
            //             projectId: this.projectId,
            //         }
            //     }, () => {
            //         getProjectOne({ projectId: this.projectId })
            //             .then(res => {
            //                 const data = res.data
            //                 this.projectName = data.name
            //                 this.apiTreeRootId = data.apiTreeId
            //             })
            //         this.addTab('开始', '-10')
            //     }, (err) => {
            //         console.log(err)
            //     })
            // } else {
                
            // }
            this.addTab('开始', Date.now() * -1 + '')
                getProjectOne({ projectId: this.projectId })
                    .then(res => {
                        const data = res.data
                        this.projectName = data.name
                        this.apiTreeRootId = data.apiTreeId
                        this.fetchLazyTree({data: {}})
                    })


            getProjectEnvList({ projectId: this.projectId })
                .then(res => {
                    const data = res.data
                    this.envOptionList = data.list
                    const selectOne = localStorage.getItem(`project.env.${this.projectId}`)
                    if (selectOne) {
                        this.envId = Number(selectOne)
                        this.fetchProjectEnvOne()
                    }
                })
            
        },

        fetchProjectEnvOne() {
            localStorage.setItem(`project.env.${this.projectId}`, this.envId)
            getProjectEnvOne({ id: this.envId })
                .then(res => {
                    this.env = res.data
                })
        },

        // fetchSortList() {
        //     return getApiTree({ projectId: this.projectId })
        //         .then(res => {
        //             const list = res.data.list
        //             this.sortList = list
        //             const route = router.currentRoute
        //             if (this.sortList.length !== 0) {
        //                 if (route.name === 'api-list' && !route.query.tagId) {
        //                     const data = {
        //                         type: 'tag',
        //                         id: this.sortList[0].id
        //                     }
        //                     this.setData(data)
        //                     this.onNodeClick(data)
        //                 } else if (route.name === 'api-list' && route.query.tagId) {
        //                     const data = {
        //                         type: 'tag',
        //                         id: route.query.tagId
        //                     }
        //                     this.setData(data)
        //                     this.onNodeClick(data)
        //                 }
        //                 if (['api-detail-prev', 'api-detail-edit', 'api-detail-run'].includes(route.name) && !route.query.docId) {
        //                     const sort = this.sortList.find(item => item[0])
        //                     this.setData(sort[0])
        //                     this.onNodeClick(data)
        //                 } else if (['api-detail-prev', 'api-detail-edit', 'api-detail-run'].includes(route.name) && route.query.docId) {
        //                     const data = {
        //                         type: 'api',
        //                         id: route.query.docId
        //                     }
        //                     this.setData(data)
        //                     this.onNodeClick(data)
        //                 }
        //             }
        //         })

        // },
        fetchDoc() {
            this.doc = null
            return getApiDoc({ id: this.docId })
                    .then(res => {
                        const data = res.data
                        this.doc = data
                    })

        },
        fetchDocList(params = {}) {
            getApiDocList({
                tagId: this.tagId,
                projectId: this.projectId,
                ...this.docPageQuery,
                ...params,
            }).then(res => {
                const data = res.data
                this.docTotal = data.total
                this.docList = data.list
            })
        },
        onNodeClick(data) {
            if (data.type === 'tag') {
                this.docPageQuery.page = 1
                this.setData(data)
                this.fetchDocList()
                router.replace({
                    name: 'api-list',
                    query: {
                        ...router.currentRoute.query,
                        tagId: data.id,
                    }
                })
            } else if (data.type === 'api') {
                this.setData(data)
                router.replace({
                    name: 'api-detail',
                    query: {
                        ...router.currentRoute.query,
                        docId: data.id,
                    }
                })
            }
        },
        // getTagList() {
        //     return getApiTagList({
        //         projectId: this.projectId,
        //     }).then(res => {
        //         this.tagList = res.data.list
        //     })
        // },
        navToApiPrev(docId) {
            this.onNodeClick({
                type: 'api',
                id: docId
            })
        },
        createApiDoc({ tagId, summary, path, method }) {
            return addApiDoc({
                projectId: this.projectId,
                tagId,
                summary,
                path,
                method
            })
        },
        updateApiDoc({ tagId, summary, path, method, parameters, requestBody, responses, statusId }) {
            return updateApiDoc({
                projectId: this.projectId,
                docId: this.docId,
                tagId,
                summary,
                path,
                method,
                parameters,
                requestBody,
                responses,
                statusId
            })
        },
        routerReplace(name, query = {}) {
            router.replace({
                name,
                query: {
                    projectId: this.projectId,
                    tagId: this.tagId,
                    docId: this.docId,
                    ...query
                }
            })
        }
    },
})